from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from model import Book, Hero

# 1. 链接数据库等准备工作
engine = create_engine('mysql+pymysql://root:python@localhost:3306/19python')
DBSession = sessionmaker(bind=engine)
session = DBSession()

# 2. 插入数据
# 创建图书1
book = Book(name="三国演义")
# 创建图书的英雄
hero01 = Hero(name="刘备", age=30, book=book)
hero02 = Hero(name="关羽", age=28, book=book)
hero03 = Hero(name="张飞", age=35, book=book)
hero04 = Hero(name="赵云", age=29, book=book)
hero05 = Hero(name="曹操", age=31, book=book)
session.add_all([book, hero01, hero02, hero03, hero04, hero05])

# 创建图书2
book1 = Book(name="封神榜")
# 创建图书的英雄
hero06 = Hero(name="姜子牙", age=20, book=book1)
hero07 = Hero(name="哪吒", age=18, book=book1)
hero08 = Hero(name="二郎神", age=25, book=book1)
session.add_all([book1, hero06, hero07, hero08])

# 额外添加3个没有添加书名的英雄
hero09 = Hero(name="达摩", age=20)
hero10 = Hero(name="花木兰", age=18)
hero11 = Hero(name="盘古", age=25)
session.add_all([hero09, hero10, hero11])

# 3. 提交（只要是增删改任意一种都意味着对数据进行了修改，都需要commit）
session.commit()

# 4. 关闭session
session.close()
